package ch.rheintalconnection.sysventory.technicalServices;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

import org.apache.commons.net.util.SubnetUtils;
import org.apache.commons.net.util.SubnetUtils.SubnetInfo;

import ch.rheintalconnection.sysventory.technicalServices.wmi.WMIHostScanner;
 
public class IpScanner implements IIpScanner {
			 

	public List<IHostScanner> scanIps(String ipmask) {
		
		SubnetUtils utils = new SubnetUtils(ipmask);
        SubnetInfo info = utils.getInfo();
        
        
        String[] ips = info.getAllAddresses();

        ExecutorService executor = Executors.newFixedThreadPool(ips.length);
        List<FutureTask<WMIHostScanner>> taskList = new ArrayList<FutureTask<WMIHostScanner>>();
        
        for (String ip : ips) {
        	
        	FutureTask<WMIHostScanner> futureTask = new FutureTask<WMIHostScanner>(new ConnectionChecker(ip));
        	taskList.add(futureTask);
        	executor.execute(futureTask);
		}
        
        ArrayList<IHostScanner> hostscanners = new ArrayList<IHostScanner>();
        
        for (FutureTask<WMIHostScanner> futureTask : taskList) {
			
        	try {
				WMIHostScanner hostScanner = futureTask.get();
				
				if (hostScanner != null) {
					hostscanners.add(hostScanner);
				}
				
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}
        executor.shutdown();
        
        return hostscanners;
	}
}